<template>
  <div>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="130px"
      class="demo-ruleForm"
      size="mini"
    >
      <el-form-item label="所属学校" prop="deptId">
        <el-select v-model="ruleForm.deptId" placeholder="请选择学校" clearable>
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item,index) in schoolList"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="年级" prop="gradeName">
        <el-input v-model="ruleForm.gradeName" placeholder="请输入年级" clearable></el-input>
      </el-form-item>

      <el-form-item label="添加所属班级" prop="cc">
        <div>
          <template>
            <el-table :data="tableData" stripe style="width: 100%">
              <el-table-column prop="name" label="班级">
                <template slot-scope="scope">
                  <el-input
                    v-model="classData['name'+scope.$index]"
                    placeholder="例如：一班"
                    size="mini"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="num" label="人数">
                <template slot-scope="scope">
                  <el-input
                    v-model="classData['numm'+scope.$index]"
                    placeholder="请输入人数"
                    size="mini"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column fixed="right" :label="$t('action.operation')">
                <template slot-scope="scope">
                  <span
                    style="cursor:pointer;color:#1da8ea"
                    @click="deleteRow(scope.$index)"
                  >{{$t('action.delete')}}</span>
                </template>
              </el-table-column>
            </el-table>
          </template>

          <div class="add" @click="addData">+</div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetForm('ruleForm')">{{$t("action.reset")}}</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">{{$t("action.save")}}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import { format } from "@/utils/datetime";

export default {
  name: "edit",
  props: {
    msg: ""
  },
  data() {
    return {
      url: this.$Config.url,
      id: "", //修改对应的id
      initDataStatus:0,//控制编辑时候是否有数据0 是初始化没数据 1是初始化有数据
      ruleForm: {
        deptId: "",
        gradeName: ""
      },
      schoolList: [], //学校列表
      classData: {},
      rules: {
        deptId: [{ required: true, message: "请选择学校", trigger: "change" }],
        gradeName: [{ required: true, message: "请输入年级", trigger: "blur" }]
      },
      tableData: [{},{},{}],
      classLength: 0 //增加班级列表的长度
    };
  },
  mounted() {
    this.getSchool();
  },
  methods: {
    getSchool() {
      const that = this;
      this.$axios
        .get(that.url + "/admin/dept/list", {
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.data.code == 200) {
            that.schoolList = res.data.data;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    deleteRow(index) {
      let id = this.classData["idid" + index];
      if (id == "" || id == undefined) {
        console.log(this.classData)
        let data = {}
        let arr = this.tableData
        for(let i = index; i< arr.length;i++){
          let next = i+1
          this.classData["name" + i] = this.classData["name" + next]
          this.classData["numm" + i] = this.classData["numm" + next]
        }
        delete this.classData["name" + arr.length]
        delete this.classData["numm" + arr.length]
        arr.splice(index,1)
        this.tableData = arr
        //this.resetData(this.id);
        return;
      }
      this.$confirm("您确认要删除该班级吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteClass(id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    deleteClass(id) {
      const that = this;
      this.$axios
        .post(
          that.url + "/admin/class/delete/{id}",
          that.$qs.stringify({ id }),
          {
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          }
        )
        .then(function(res) {
          if (res.data.code == 200) {
            that.$message({
              type: "success",
              message: "删除成功!"
            });
            that.resetData(that.id);
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    addData() {
      this.tableData.push({});
      this.classLength = this.tableData.length - 1;
      this.classData["idid" + this.classLength] = "";
    },
    resetData(id = 1) {
      this.$refs["ruleForm"].resetFields();//先清空
      const that = this;
      this.id = id;
      this.classData = {};
      this.$axios
        .get(that.url + "/admin/class/getByGradeId", {
          params: {
            gradeId: id
          },
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.data.code === 200) {
            let data = res.data.data;
            that.id = data.id;
            that.ruleForm.deptId = data.deptId;
            that.ruleForm.gradeName = data.name;

            that.tableData = [];
            if (data.classList.length == 0) {
              that.initDataStatus=0;//初始化没数据
              that.tableData.push({});
            } else {
              that.initDataStatus=1;//初始化有数据
              for (let i = 0; i < data.classList.length; i++) {
                that.tableData.push({});
                let obj = {
                  ["name" + i]: data.classList[i].name,
                  ["numm" + i]: data.classList[i].count,
                  ["idid" + i]: data.classList[i].id
                };
                that.classData = { ...that.classData, ...obj };
              }
            }
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    submitForm(formName) {
      const that = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (that.id == "") {
            that.add();
          } else {
            that.updateData();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    updateData() {
      const that = this;
      let arr = [];
      let obj1 = {};

      console.log(this.classData )
      for (let key in this.classData) {

        if (key.slice(0, 4) == "name") {
          obj1.name = this.classData[key];
        }
        if (key.slice(0, 4) == "numm") {
          obj1.number = this.classData[key];
        }
        if (key.slice(0, 4) == "idid") {
          obj1.id = this.classData[key];
        }

        if (Object.keys(obj1).length == 3) {
          arr.push(obj1);
          obj1 = {};
        }
        if(that.initDataStatus==0){
          if (Object.keys(obj1).length == 2) {
            arr.push(obj1);
            obj1 = {};
          }
        }

      }

      let data = {
        gradeId: this.id,
        deptId: that.ruleForm.deptId,
        gradeName: that.ruleForm.gradeName,
        classInfo: JSON.stringify(arr)
      };
      this.$axios
        .post(
          that.url + "/admin/class/saveOrUpdate",
          that.$qs.stringify(data),
          {
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          }
        )
        .then(function(res) {
          if (res.status == 200) {
            if (that.msg == 1) {
              that.$message({
                message: "添加成功",
                type: "success"
              });
            } else {
              that.$message({
                message: "修改成功",
                type: "success"
              });
            }
            that.$emit("hideEdit", false);
          } else {
            that.$message({
              message: res.statusText,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    add() {
      const that = this;
      let arr = [];
      let obj = {
        name: "",
        number: ""
      };
      let RootData = Object.entries(this.classData);
      RootData.forEach((item, index) => {
        if (item[0].slice(0, 4) == "name") {
          obj.name = item[1];
        }
        if (item[0].slice(0, 4) == "numm") {
          obj.number = item[1];
          arr.push(obj);
          obj = {
            name: "",
            number: ""
          };
        }
      });
      if (arr.length == 0) {
        that.$message({
          message: "请输入班级名称以及人数",
          type: "warning"
        });
        return;
      }
      let data = {
        gradeId: this.id,
        deptId: that.ruleForm.deptId,
        gradeName: that.ruleForm.gradeName,
        classInfo: JSON.stringify(arr)
      };

      this.$axios
        .post(
          that.url + "/admin/class/saveOrUpdate",
          that.$qs.stringify(data),
          {
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          }
        )
        .then(function(res) {
          if (res.status == 200) {
            if (that.msg == 1) {
              that.$message({
                message: "添加成功",
                type: "success"
              });
            } else {
              that.$message({
                message: "修改成功",
                type: "success"
              });
            }
            that.$emit("hideEdit", false);
          } else {
            that.$message({
              message: res.statusText,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      //    新增
      this.id = "";
      this.tableData = [{}];
      this.classData = {};
    }
  }
};
</script>

<style scoped lang="scss">
.el-select,
.el-date-editor {
  width: 100%;
}

.add {
  text-align: center;
  color: #666;
  font-size: 30px;
  cursor: pointer;
  background: rgba(242, 242, 242, 1);
}
</style>
